/**
 * 
 */
package ikeuilib;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;



/**
 * @author ikechan
 *
 */
public class JProgressCellRenderer extends JProgressBar implements TableCellRenderer{
	private static final long serialVersionUID = 1L;

	public JProgressCellRenderer(int min, int max){
		super(min, max);
	}

	public Component getTableCellRendererComponent(JTable table, Object value,
			boolean isSelected,boolean hasFocus, int row, int column){
		if(value instanceof Number){
			setValue(((Number) value).intValue());
		}
		return this;
	}

	public static JProgressCellRenderer install(JTable table,int min,int max){
		JProgressCellRenderer renderer=new JProgressCellRenderer(min,max);
		table.setDefaultRenderer(JProgressBar.class, renderer);
		table.setRowHeight((int) renderer.getPreferredSize().getHeight());
		return renderer;
	}
	
	public static void main(String[] args){
		JFrame f=new JFrame();
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JTable tb=new JTable();
		final DefaultTableModel model=new DefaultTableModel(){
			private static final long serialVersionUID = 1L;
			@Override
			public boolean isCellEditable(int arg0, int arg1) {
				return false;
			}
			@Override
			public Class<?> getColumnClass(int arg0) {
				if(arg0==1){
					return JProgressBar.class;
				}else{
					return super.getColumnClass(arg0);
				}
			}
			
		};
		model.setColumnCount(2);
		model.setRowCount(1);
		model.setColumnIdentifiers(new String[]{"Name","Value"});
		JProgressCellRenderer rend=JProgressCellRenderer.install(tb, 0, 100);
		rend.setStringPainted(true);
		model.setValueAt("Progress", 0, 0);
		model.setValueAt(rend, 0, 1);
		tb.setModel(model);
		f.getContentPane().setLayout(new BorderLayout());
		f.getContentPane().add(new JScrollPane(tb),BorderLayout.CENTER);
		f.setTitle("Test");
		f.setSize(300,200);
		f.setLocationRelativeTo(null);
		f.addComponentListener(new ComponentListener(){
			int id=0;
			@Override
			public void componentHidden(ComponentEvent arg0) {}
			@Override
			public void componentMoved(ComponentEvent arg0) {}
			@Override
			public void componentResized(ComponentEvent arg0) {}
			@Override
			public void componentShown(ComponentEvent arg0) {
				Runnable r=new Runnable(){
					public void run(){
						while(id<100){
							model.setValueAt(++id, 0, 1);
							try{
								Thread.sleep(250);
							}catch(Exception e){
								e.printStackTrace();
							}
						}
					}
				};
				new Thread(r).start();
			}
		});
		f.setVisible(true);
	}
	
}
